package cn.yulr.log;

import android.os.Environment;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;

/**
 * 日志类
 * 用来替换系统的日志类
 * <p>
 * 此部分包含三个部分的任务
 * 1. 检测文件夹是否存在，如果不存在创建相关路径
 * 2. 检测日志文件的大小、数量、总大小等等相关信息
 * 3. 以UDP的形式，发送日志信息到指定的远端设备
 * <p>
 * 日志的内容格式
 * LOGTAG_LOGINFO 通过日志Tag加上日志内容，通过 _ 来执行分割
 *
 * <p>
 * 第一部分
 * 日志的路径信息，暂时确定在 SD卡 的某个目录中间
 * <p>
 * 第二部分
 * 日志的文件信息，按照 时间_TAG.log 的格式来保存，TAG 为执行应用的标识信息
 * 如果日志信息 达到指定大小或者应用重启或者系统重启，将会重新开始记录
 * 日志的总内容，原则上大小不超过 500M
 * 如果日志数量达到了 500M ，将会删除最初开始部分的日志信息
 * <p>
 * 第三部分
 * UDP形式发送数据，此部分针对不同的应用，需要区别对待，防止端口占用的情况发生
 * 同时此部分需要可以调节，在默认情况下处于关闭的状态，可以通过网络或者其他的方式执行打开操作
 * <p>
 * 暂时定义，日志信息的存储路径如下：SDCard/logS/
 * <p>
 * 当前 Lib 只能控制使用一个文件，不针对多应用模式设计
 * <p>
 * 2019.02.18 准备开始实现UDP模式下的功能
 */
public class Log {

    private final static String TAG = "XLog";

    private static final String VERBOSE = "VERBOSE";
    private static final String DEBUG = "DEBUG";
    private static final String INFO = "INFO";
    private static final String WARN = "WARN";
    private static final String ERROR = "ERROR";

    private static boolean isLogInited = false;
    private static LogConfigInfo logConfigInfo = null;

    private static LoggerCheckAndWriteThread loggerCheckAndWriteThread = null;

    /**
     * 初始化日志部分，此部分需要在 Application 中间开始执行
     * 在 Application 的第一条日志之前，初始化本部分，之后使用
     * 如果不执行初始化，将只会执行系统的部分
     *
     * @param logConfigInfo 初始化相关信息
     */
    public static void initLog(LogConfigInfo logConfigInfo) {
        if (logConfigInfo == null) return;
        Log.logConfigInfo = logConfigInfo;
        initLog();
    }


    public static boolean isLogInited() {
        return isLogInited;
    }

    /**
     * 释放相关资源
     */
    public static void release() {
        isLogInited = false;
        if (loggerCheckAndWriteThread != null) {
            try {
                loggerCheckAndWriteThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            loggerCheckAndWriteThread = null;
        }
    }

    /**
     * SD卡路径信息
     */
    private static String sdDir;

    /**
     * 日志的文件路径为 SDCard/APP_TAG/
     */
    private static void initLog() {

        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory().getAbsolutePath();//获取跟目录
        } else {
            sdDir = "/system";
        }

//        sdDir = "/system";
        sdDir = sdDir + "/logS/";
        File logTotalFolder = new File(sdDir);
        if (logTotalFolder.exists()) {
            e(TAG, "日志总目录 " + sdDir + " 存在，不执行目录创建操作", false);
        } else {
            boolean result = logTotalFolder.mkdir();
            if (result) {
                e(TAG, "创建路径成功，准备开始执行创建应用日志文件夹", false);
            } else {
                e(TAG, "创建路径失败");
            }
        }

        sdDir = sdDir + "/" + logConfigInfo.getAppTag() + "/";

        e(TAG, "找到SD卡位置，初始化写入和查询线程部分:" + sdDir, false);
//        e(TAG, "准备写入日志到目录：" + sdDir);
        File loggerFile = new File(sdDir);
        if (loggerFile.exists()) {
            e(TAG, "文件路径存在，不需要执行其他操作，准备开始执行", false);
            isLogInited = true;
        } else {
            e(TAG, "文件路径不存在，执行创建路径流程", false);
            boolean result = loggerFile.mkdir();
            if (result) {
                e(TAG, "创建路径成功，准备开始执行", false);
                isLogInited = true;
            } else {
                e(TAG, "创建路径失败", false);
            }
        }

        if (isLogInited) {
            loggerCheckAndWriteThread = new LoggerCheckAndWriteThread();
            loggerCheckAndWriteThread.start();
        }

//            logCheckThread = new Thread() {
//
//                private LogRequestBean logRequestBean = null;
//                private final AtomicBoolean atomicBoolean = new AtomicBoolean(false); // 变量控制
//                private UDPUnicastTools udpUnicastTools = null;
//                private MHttpServer httpServer = null;
//                private HttpRequestAsyncRequestHander deviceUpdateHttpRequestAsyncRequestHander = new HttpRequestAsyncRequestHander("/log");
//                private AbsHttpRequestActionListener httpRequestActionListener = new AbsHttpRequestActionListener() {
//                    @Override
//                    public boolean onHttpRequestAction(String requestAction, HttpRequest httpRequest, HttpResponse httpResponse, HttpContext context) {
//                        if (CommonMethods.isStringNotEmpty(requestAction) && (requestAction.equals("/log"))) {
//                            httpResponse.setStatusCode(HttpStatus.SC_OK);
//                            String method = httpRequest.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
//
//                            if (!method.equals("POST")) {
//                                httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.RESULT_ERROR_METHOD_ERROR);
//                            } else {
//
//                                Header[] headers = httpRequest.getAllHeaders();
//
//                                String sDeviceSerial = null;
//                                String deviceSerial = null;
//                                String callMethod = null;
//
//                                for (Header header : headers) {
//                                    if (header != null && header.getValue() != null) {
//                                        if (header.getName().equals(IntercomHttp.S_DEVICESERIAL)) {
//                                            sDeviceSerial = header.getValue();
//                                        } else if (header.getName().equals(IntercomHttp._DEVICESERIAL)) {
//                                            deviceSerial = header.getValue();
//                                        } else if (header.getName().equals(IntercomHttp.METHOD_OPERATPR)) {
//                                            callMethod = header.getValue();
//                                        } else if (header.getName().startsWith("TAG_")) {
//                                            httpResponse.addHeader(header);
//                                        }
//                                    }
//                                }
//
//                                httpResponse.addHeader(IntercomHttp.S_DEVICESERIAL, deviceSerial);
//                                httpResponse.addHeader(IntercomHttp._DEVICESERIAL, sDeviceSerial);
//                                httpResponse.addHeader(IntercomHttp.METHOD_OPERATPR, callMethod);
//
//                                String requestContent = getRequestContent(httpRequest);
//
//                                if (CommonMethods.isStringNotEmpty(callMethod)) {
//                                    switch (callMethod) {
//                                        case IntercomHttp.CALL_METHOD_GET_LOG_STATE:
//                                            if (logRequestBean != null) {
//                                                NStringEntity logRequestBeanEntity = new NStringEntity(new Gson().toJson(logRequestBean), ContentType.create("application/json", "UTF-8"));
//                                                httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.RESULT_SUCCESSED);
//                                                httpResponse.setEntity(logRequestBeanEntity);
//                                            } else {
//                                                httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.GET_LOG_STATE_NULL);
//                                            }
//                                            break;
//                                        case IntercomHttp.CALL_METHOD_SET_LOG_STATE:
//                                            if (CommonMethods.isStringNotEmpty(requestContent)) {
//                                                // 初始化状态
//                                                if (logRequestBean != null) {
//                                                    // 已经存在对象，不执行重复定义
//                                                    httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.SET_LOG_STATE_FAILED_EXIST);
//                                                } else {
//                                                    android.util.Log.e(TAG, "onHttpRequestAction: 接收到日志配置：" + requestContent);
//                                                    final LogRequestBean tempLogRequestBean = new Gson().fromJson(requestContent, LogRequestBean.class);
//                                                    if (tempLogRequestBean == null) {
//                                                        httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.SET_LOG_STATE_FAILED_CONTENT_ERROR);
//                                                    } else {
//                                                        if (tempLogRequestBean.getPort() > 0 && CommonMethods.isStringNotEmpty(tempLogRequestBean.getServerIp())) {
//                                                            synchronized (atomicBoolean) {
//                                                                logRequestBean = tempLogRequestBean;
//                                                                httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.RESULT_SUCCESSED);
//                                                            }
//                                                        }
//                                                    }
//                                                }
//                                            } else {
//                                                // 为 NULL，为关闭状态
//                                                synchronized (atomicBoolean) {
//                                                    logRequestBean = null;
//                                                    httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.RESULT_SUCCESSED);
//                                                }
//                                            }
//                                            break;
//                                    }
//                                } else {
//                                    httpResponse.addHeader(IntercomHttp.RESULT_ContentType, IntercomHttp.RESULT_ERROR_MAIN_METHOD_NULL);
//                                }
//
//                            }
//
//                        }
//                        return true;
//                    }
//                };
//
//
//                @Override
//                public void run() {
//
//                    boolean isDirExist = false;
//
//                    //region 检查相关文件夹是否存在，如果不存在执行创建操作
//                    File logFloder = new File(sdDir + "/logS/");
////                    if (!(logFloder.exists() && logFloder.isDirectory())) {
////                        // 不存在 相关文件夹信息 执行文件夹创建操作
////                        if (logFloder.mkdirs()) {
////                            android.util.Log.e(TAG, "LogThread.run: 创建日志相关路径成功");
////                        } else {
////                            android.util.Log.e(TAG, "LogThread.run: 创建日志相关路径失败");
////                        }
////                    } else {
////                        android.util.Log.e(TAG, "LogThread.run: 日志相关路径信息存在，不需要执行创建操作");
////                        isDirExist = true;
////                    }
//                    //endregion
//
//                    if (isDirExist) {
//                        dirSizeControl(logFloder);
//                    }
//
//                    if (CommonMethods.isStringNotEmpty(logConfigInfo.getLocalIpAddr())) {
//
//                        // IP地址存在，可以执行网络部分内容
//
//                        if (logConfigInfo.getHttpPort() > 0) {
//                            httpServer = new MHttpServer();
//                            deviceUpdateHttpRequestAsyncRequestHander.addHttpRequestActionFinishedListener(httpRequestActionListener);
//                            httpServer.add(deviceUpdateHttpRequestAsyncRequestHander);
//                            httpServer.initHttpServer(logConfigInfo.getHttpPort(), logConfigInfo.getLocalIpAddr(), "LOG_SERVER_V0.1");
//                        }
//
//                        if (logConfigInfo.getUDPPort() > 0) {
//                            udpUnicastTools = new UDPUnicastTools(logConfigInfo.getLocalIpAddr(), logConfigInfo.getUDPPort());
//                            udpUnicastTools.addUnicastCallback(new UDPUnicastTools.UnicastCallback() {
//                                @Override
//                                public void onReceive(byte[] bytes) {
//                                    if (bytes == null) return;
//                                    if (bytes.length == 5) {
//                                        if (bytes[0] == (byte) 0 && bytes[1] == (byte) 0 &&
//                                                bytes[2] == (byte) 0 && bytes[3] == (byte) 0 &&
//                                                bytes[4] == (byte) 0) {
//                                            // 为 NULL，为关闭状态
//                                            synchronized (atomicBoolean) {
//                                                logRequestBean = null;
//                                            }
//                                        }
//                                    } else {
//                                        String content = new String(bytes);
//                                        if (CommonMethods.isStringNotEmpty(content)) {
//                                            LogRequestBean tempLogRequestBean = new Gson().fromJson(content, LogRequestBean.class);
//                                            if (tempLogRequestBean != null) {
//                                                if (tempLogRequestBean.getPort() > 0 && CommonMethods.isStringNotEmpty(tempLogRequestBean.getServerIp())) {
//                                                    synchronized (atomicBoolean) {
//                                                        logRequestBean = tempLogRequestBean;
//                                                    }
//                                                }
//                                            }
//                                        }
//                                    }
//                                }
//                            });
//                        }
//                    }
//                    File logFile = getNewLogFile();
//                    try {
//                        BufferedWriter logWriter = new BufferedWriter(new FileWriter(logFile));
//                        while (isLogInited) {
//                            LogBean logBean;
//                            synchronized (logQueue) {
//                                logBean = logQueue.poll();
//                            }
//                            if (logBean != null) {
//                                String logInfo = logBean.l + " " + logBean.a + " " + logBean.t + " " + logBean.i;
//                                if (!logBean.i.endsWith("\n")) {
//                                    logInfo = logInfo + "\n";
//                                }
////                                android.util.Log.e(TAG, "run: 写入日志：" + logBean.i);
//                                logWriter.write(logInfo);
//                                synchronized (atomicBoolean) {
//                                    if (logRequestBean != null) {
//                                        udpUnicastTools.sendAsyn(logRequestBean.getServerIp(), logRequestBean.getPort(), logInfo.getBytes());
//                                    }
//                                }
//
//                                if (logFile.length() / 1024 / 1024 > logConfigInfo.getMaxFilesSize()) {
//                                    logWriter.close();
//                                    logFile = getNewLogFile();
//                                    logWriter = new BufferedWriter(new FileWriter(logFile));
//                                    dirSizeControl(logFloder);
//                                }
//                            } else {
//                                TimeUnit.SECONDS.sleep(1);
//                            }
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                private File getNewLogFile() {
//                    File logFile = new File(sdDir + "/logS/" + System.currentTimeMillis() + "_" + logConfigInfo.getAppTag() + ".log");
//                    while (logFile.exists()) {
//                        logFile = new File(sdDir + "/logS/" + System.currentTimeMillis() + "_" + logConfigInfo.getAppTag() + ".log");
//                    }
//                    return logFile;
//                }
//
//                /**
//                 * 文件夹控制
//                 * 此部分主要负责删除超出大小情况下的文件信息
//                 *
//                 * 此部分检测时，需要注意，不要删除当前正在写入的文件信息
//                 *
//                 * 此部分主要用来删除多出来的部分
//                 *
//                 * @param logFloder 文件夹路径
//                 */
//                private void dirSizeControl(File logFloder) {
//                    File[] logFiles = logFloder.listFiles();
//                    if (logFiles != null && logFiles.length > 0) {
//                        List<File> appLogFileList = new ArrayList<>();
//                        float totalFileSize = 0;
//                        for (File file : logFiles) {
//                            if (file.getName().contains(logConfigInfo.getAppTag())) {
//                                appLogFileList.add(file);
//                                totalFileSize += file.length();
//                            }
//                        }
//                        float totalFileSizeMB = totalFileSize / 1024 / 1024;
//                        android.util.Log.e(TAG, "dirSizeControl: 当前应用总日志文件大小：" + totalFileSizeMB + "MB");
//                        // 日志达到 指定的大小(500MB)，删除一部分(100MB)
//                        if (totalFileSizeMB > logConfigInfo.getMaxFilesSize()) {
//                            File[] appLogFiles = (File[]) appLogFileList.toArray();
//                            if (appLogFiles != null) {
//                                Arrays.sort(appLogFiles, new Comparator<File>() {
//                                    @Override
//                                    public int compare(File o1, File o2) {
//                                        String nameO1 = o1.getName();
//                                        String nameO2 = o2.getName();
//                                        long time1 = Long.parseLong(nameO1.split("_")[0]);
//                                        long time2 = Long.parseLong(nameO2.split("_")[0]);
//                                        return (int) (time1 - time2);
//                                    }
//                                });
//
//                                List<File> deleteFileList = new ArrayList<>();
//                                totalFileSize = 0;
//                                for (File file : appLogFiles) {
//                                    System.out.println(file.getName());
//                                    totalFileSize += file.length();
//                                    deleteFileList.add(file);
//                                    if (totalFileSize >= 524288) {
//                                        break;
//                                    }
//                                }
//
//                                for (File deleteFile : deleteFileList) {
//                                    android.util.Log.e(TAG, "删除文件：" + deleteFile.getName());
//                                    deleteFile.delete();
//                                }
//                            }
//                        }
//                    }
//                }
//            };
//            logCheckThread.start();
//            isLogInited = true;

    }

    private static class LoggerCheckAndWriteThread extends Thread {

        @Override
        public void run() {

            File logFloder = new File(sdDir);

            dirSizeControl(logFloder);

            File logFile = getNewLogFile();

            long startTimeStamp = System.currentTimeMillis();

            try {
                FileWriter logWriter = new FileWriter(logFile);

                int writeCount = 1;

                while (isLogInited) {

                    startTimeStamp = System.currentTimeMillis();
                    LogBean logBean;
                    synchronized (logQueue) {
                        logBean = logQueue.poll();
                    }

                    if (logBean != null) {
                        String logInfo = logBean.l + " " + logBean.a + " " + logBean.t + " " + logBean.i;
                        if (!logBean.i.endsWith("\n")) {
                            logInfo = logInfo + "\n";
                        }

                        logWriter.write(logInfo);
                        logWriter.flush();

//                        synchronized (atomicBoolean) {
//                            if (logRequestBean != null) {
//                                udpUnicastTools.sendAsyn(logRequestBean.getServerIp(), logRequestBean.getPort(), logInfo.getBytes());
//                            }
//                        }

                        if ((++writeCount) % 100 == 0) {
                            if (logFile.length() / 1024 / 1024 > logConfigInfo.getMaxFilesSize()) {
                                logWriter.close();
                                logFile = getNewLogFile();
                                logWriter = new FileWriter(logFile);
                                dirSizeControl(logFloder);
                            }
                            writeCount = 1;
                        }

                        try {
                            TimeUnit.MILLISECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    } else {
                        try {
                            TimeUnit.MILLISECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
                logWriter.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS", Locale.CHINA);

    private static String getFormattedCurrentTime() {
        return formatter.format(new Date(System.currentTimeMillis()));
    }

    private static File getNewLogFile() {
        File logFile = new File(sdDir + getFormattedCurrentTime() + "_" + logConfigInfo.getAppTag() + ".log");
        while (logFile.exists()) {
            logFile = new File(sdDir + getFormattedCurrentTime() + "_" + logConfigInfo.getAppTag() + ".log");
        }

        try {
            boolean result = logFile.createNewFile();
            if (result) {
                e(TAG, "创建新文件成功", false);
            } else {
                e(TAG, "创建新文件失败", false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return logFile;
    }

    /**
     * 文件夹控制
     * 此部分主要负责删除超出大小情况下的文件信息
     * <p>
     * 此部分检测时，需要注意，不要删除当前正在写入的文件信息
     * <p>
     * 此部分主要用来删除多出来的部分
     *
     * @param logFloder 文件夹路径
     */
    private static void dirSizeControl(File logFloder) {
        File[] logFiles = logFloder.listFiles();
        if (logFiles != null && logFiles.length > 0) {
            List<File> appLogFileList = new ArrayList<>();
            float totalFileSize = 0;
            for (File file : logFiles) {
                if (file.getName().contains(logConfigInfo.getAppTag())) {
                    appLogFileList.add(file);
                    totalFileSize += file.length();
                }
            }
            float totalFileSizeMB = totalFileSize / 1024 / 1024;
            e(TAG, "dirSizeControl: 当前应用总日志文件大小：" + totalFileSizeMB + "MB", false);
            // 日志达到 指定的大小(500MB)，删除一部分(100MB)
            if (totalFileSizeMB > logConfigInfo.getMaxFilesSize()) {
                File[] appLogFiles = (File[]) appLogFileList.toArray();
                if (appLogFiles != null) {
                    Arrays.sort(appLogFiles, new Comparator<File>() {
                        @Override
                        public int compare(File o1, File o2) {
                            String nameO1 = o1.getName();
                            String nameO2 = o2.getName();
                            long time1 = Long.parseLong(nameO1.split(".")[0]);
                            long time2 = Long.parseLong(nameO2.split(".")[0]);
                            return (int) (time1 - time2);
                        }
                    });

                    List<File> deleteFileList = new ArrayList<>();
                    totalFileSize = 0;
                    for (File file : appLogFiles) {
                        System.out.println(file.getName());
                        totalFileSize += file.length();
                        deleteFileList.add(file);
                        if (totalFileSize >= 524288) {
                            break;
                        }
                    }

                    for (File deleteFile : deleteFileList) {
                        android.util.Log.e(TAG, "删除文件：" + deleteFile.getName());
                        boolean result = deleteFile.delete();
                        if (result) {
                            i(TAG, "删除超出部分的日志内容成功", false);
                        } else {
                            i(TAG, "删除超出部分的日志内容失败", false);
                        }
                    }
                }
            }
        }
    }

    /**
     * 日志队列，此部分主要针对日志保存以及相关信息
     */
    private final static Queue<LogBean> logQueue = new ConcurrentLinkedQueue<>();

    public static void v(String tag, String msg, boolean isNeedWrite) {
        android.util.Log.v(tag, msg);
        if (isLogInited && isNeedWrite) {
            addLogBean(new LogBean(Log.logConfigInfo.getAppTag(), VERBOSE, tag, msg));
        }
    }

    public static void v(String tag, String msg) {
        v(tag, msg, true);
    }

    public static void v(String msg) {
        StackTraceElement a = Thread.currentThread().getStackTrace()[3];
        String logTag = getClassName(a.getClassName()) + "." + a.getMethodName() + "-" + a.getLineNumber();
        v(logTag, msg);
    }

    public static void d(String tag, String msg, boolean isNeedWrite) {
        android.util.Log.d(tag, msg);
        if (isLogInited && isNeedWrite) {
            addLogBean(new LogBean(Log.logConfigInfo.getAppTag(), DEBUG, tag, msg));
        }
    }

    public static void d(String tag, String msg) {
        d(tag, msg, true);
    }

    public static void d(String msg) {
        StackTraceElement a = Thread.currentThread().getStackTrace()[3];
        String logTag = getClassName(a.getClassName()) + "." + a.getMethodName() + "-" + a.getLineNumber();
        d(logTag, msg);
    }

    public static void i(String tag, String msg, boolean isNeedWrite) {
        android.util.Log.i(tag, msg);
        if (isLogInited && isNeedWrite) {
            addLogBean(new LogBean(Log.logConfigInfo.getAppTag(), INFO, tag, msg));
        }
    }

    public static void i(String tag, String msg) {
        i(tag, msg, true);
    }

    public static void i(String msg) {
        StackTraceElement a = Thread.currentThread().getStackTrace()[3];
        String logTag = getClassName(a.getClassName()) + "." + a.getMethodName() + "-" + a.getLineNumber();
        i(logTag, msg);
    }

    public static void w(String tag, String msg, boolean isNeedWrite) {
        android.util.Log.w(tag, msg);
        if (isLogInited && isNeedWrite) {
            addLogBean(new LogBean(Log.logConfigInfo.getAppTag(), WARN, tag, msg));
        }
    }

    public static void w(String tag, String msg) {
        w(tag, msg, true);
    }

    public static void w(String msg) {
        StackTraceElement a = Thread.currentThread().getStackTrace()[3];
        String logTag = getClassName(a.getClassName()) + "." + a.getMethodName() + "-" + a.getLineNumber();
        w(logTag, msg);
    }

    public static void e(String tag, String msg, boolean isNeedWrite) {
        android.util.Log.e(tag, msg);
        if (isLogInited && isNeedWrite) {
            addLogBean(new LogBean(Log.logConfigInfo.getAppTag(), ERROR, tag, msg));
        }
    }

    public static void e(String tag, String msg) {
        e(tag, msg, true);
    }

    public static void e(String msg) {
        StackTraceElement a = Thread.currentThread().getStackTrace()[3];
        String logTag = getClassName(a.getClassName()) + "." + a.getMethodName() + "-" + a.getLineNumber();
        e(logTag, msg);
    }

    private static void addLogBean(LogBean logBean) {
        if (logBean == null) return;
        synchronized (logQueue) {
            logQueue.offer(logBean);
        }
    }

    public static String getClassName(String className) {
        if (className != null && !"".equals(className)) {
            return className.substring(className.lastIndexOf(".") + 1);
        }
        return "";
    }

}
